// loading indication

// bool which dictates if on the next successful update, the loading class should be hid
// std is true, so when it does update for the first time, they are hid
// reset only in successfulUpdate
var __hideLoadingOnNextUpdate = true;
function hideLoadingOnNextUpdate() { __hideLoadingOnNextUpdate = true; }

// hiding and showing of loading items indicated by the "hideOnSuccess" class
function showLoading() {
  const toHide = document.getElementsByClassName("hideOnSuccess");
  for (var x = 0; x < toHide.length; x++) toHide[x].hidden = false;
}

function dontShowLoading() {
  const toHide = document.getElementsByClassName("hideOnSuccess");
  for (var x = 0; x < toHide.length; x++) toHide[x].hidden = true;
}

var graphBuilt = false;
function successfulUpdate(values) {
    // successful call of to getStocks
    // hardcoded lists of functions to call with the successful getStock data
    updateValues(values);
    hasLost();
    if (!graphBuilt) {
      getGraph(values);
      graphBuilt = true;
    }

    if (__hideLoadingOnNextUpdate) {
      dontShowLoading();
      __hideLoadingOnNextUpdate = false;
    }
    
    if (newStocks) {
      // list of functions to call when there are new stocks (selling, buying)
      fillStockSellSelect(values);
      getMoney();
      newStocks = false;
    }
}


// networking and update control

// reduce message passing to server:
// doesn't update while this is set to true
var lastUpdateFinished = true;
function startUpdating() {
  lastUpdateFinished = true;
}
function stopUpdating() {lastUpdateFinished = false;}

// are there new Stocks? updated from the outside
var newStocks = true;
function updateNewStocks() {newStocks = true;}

// this is purely client side: this opens the possibility for abuse
const refreshEveryMs = 500;
const updateUrl = "getStocks";

function __getValues() {
  fetch(updateUrl)
  .then(response => {
    if (response.ok) return response.json();
    else throw new Error("request failed");
  })
  .then(values => {
    successfulUpdate(values);
  })
  .catch(error => {
    startUpdating();
    // for debugging:
    //console.log("The following error occured while updating:");
    //console.log(error);
  });
}

function getValuesControl() {
  // if the last update finished, set the lock and update
  if (lastUpdateFinished) {
    stopUpdating();
    __getValues();
  }
}

getValuesControl();
// start repeating the update function
setInterval(function() {
  getValuesControl();
}, refreshEveryMs);

